import React, {useEffect, useRef, useState} from "react";
import {Alert, Dimensions, ScrollView, StyleSheet, Text, TextInput, TouchableHighlight, View} from "react-native";
import {closeeyeSvgXml, copySvgXml, openeyeSvgXml, rightSvgXml, writeGreySvgXml} from "../libs/svgXml";
import {SvgXml} from "react-native-svg";
import {fontSize_12, fontSize_14, fontSize_15, fontSize_16} from "./theme";
import {Avatar} from "react-native-elements/dist/avatar/Avatar";
import {setCopyMsg} from "../libs/utils";
import {BottomSheet} from "react-native-elements/dist/bottomSheet/BottomSheet";
import {
    checkWalletPassword, clearNowWallet,
    getChainInfo,
    getWalletInfo,
    getWalletUseFinger, initNet,
    nowWallet,
    removeWallet, updateNowWallet, useWalletType
} from "./smartxL2Libs/L2_Data";
import SimpleToast from "react-native-simple-toast";
import FingerPrintPopup from "../components/FingerPrint/FingerPrint";

const {width, height, scale} = Dimensions.get("window");

const L2_WalletDetail = ({navigation,route}: any) => {
    const [address,setAddress] = useState(route?.params?.address)
    const [name,setName] = useState(route?.params?.name)
    const [providerUrl,setProviderUrl] = useState(route?.params?.providerUrl)
    const [img,setImg] = useState(route?.params?.img)
    const [viewWallet,setViewWallet] = useState(route?.params?.viewWallet)
    //显示密码输入框
    const [showInputPassword,setShowInputPassword] = useState(false)
    const [passwordInput,setPasswordInput] = useState("")
    const [showPassword,setShowPassword] = useState(false)
    //密码input的ref
    const inputPasswordRef = useRef(null);
    //跳转到对应的页面名称和数据
    const [toViewName,setToViewName] = useState("")
    //界面
    const [WalletDetailListItem, setWalletDetailListItem] = useState([]);
    //是否使用指纹
    const [useFinger,setUseFinger] = useState(false)
    //显示指纹解锁
    const [showFinger,setShowFinger] = useState(false)
    useEffect(() => {
        navigation.setOptions({
            title:"钱包详情"
        })
        initWalletDetailListItem();
    }, [])
    const initWalletDetailListItem = async () => {
        let walletUseFinger = await getWalletUseFinger(nowWallet.chainID,nowWallet.address)
        console.log(`walletUseFinger:${walletUseFinger}`)
        setUseFinger(walletUseFinger)
        let walletInfo = await getWalletInfo(nowWallet.chainID, nowWallet.address)
        console.log("walletInfo",walletInfo)
        if(walletInfo.mnemonic)
        {
            let WalletDetailListItemTemp = [
                {
                    show:false,
                    title:"导出助记词",
                    onPress:()=>{
                        setToViewName("L2_MnemonicView")
                        if(walletUseFinger)
                        {
                            setShowFinger(true)
                            return
                        }
                        setShowInputPassword(true)
                        setTimeout(()=>{
                            console.log(inputPasswordRef)
                            inputPasswordRef && inputPasswordRef.current.focus()
                        },200)
                    },
                },
                {
                    title:"导出私钥",
                    onPress:()=>{
                        setToViewName("L2_PrivateKeyView")
                        if(walletUseFinger)
                        {
                            setShowFinger(true)
                            return
                        }
                        setShowInputPassword(true)
                        setTimeout(()=>{
                            inputPasswordRef && inputPasswordRef.current.focus()
                        },200)
                    },
                },
                {
                    title:"导出 Keystore",
                    onPress:()=>{
                        setToViewName("L2_KeystoreView")
                        if(walletUseFinger)
                        {
                            setShowFinger(true)
                            return
                        }
                        setShowInputPassword(true)
                        setTimeout(()=>{
                            inputPasswordRef && inputPasswordRef.current.focus()
                        },200)
                    },
                },
                {
                    title:"钱包同步",
                    onPress:()=>{
                        console.log(1)
                    },
                },
                {
                    dividerBottom:true,
                    title:"白名单",
                    onPress:()=>{
                        console.log(1)
                    },
                },
                {
                    title:"指纹支付",
                    onPress:()=>{
                        navigation.navigate("L2_SettingPayByFinger")
                    },
                },
                {
                    title:"修改密码",
                    onPress:()=>{
                        console.log(1)
                    },
                },
                {
                    title:"重置密码",
                    onPress:()=>{
                        console.log(1)
                    },
                },
            ];
            WalletDetailListItemTemp[0].show = true
            setWalletDetailListItem(WalletDetailListItemTemp)
            return
        }
        let WalletDetailListItemTemp = [
            {
                show:false,
                title:"导出助记词",
                onPress:()=>{
                    setToViewName("L2_MnemonicView")
                    if(walletUseFinger)
                    {
                        setShowFinger(true)
                        return
                    }
                    setShowInputPassword(true)
                    setTimeout(()=>{
                        console.log(inputPasswordRef)
                        inputPasswordRef && inputPasswordRef.current.focus()
                    },200)
                },
            },
            {
                title:"导出私钥",
                onPress:()=>{
                    setToViewName("L2_PrivateKeyView")
                    if(walletUseFinger)
                    {
                        setShowFinger(true)
                        return
                    }
                    setShowInputPassword(true)
                    setTimeout(()=>{
                        inputPasswordRef && inputPasswordRef.current.focus()
                    },200)
                },
            },
            {
                title:"导出 Keystore",
                onPress:()=>{
                    setToViewName("L2_KeystoreView")
                    if(walletUseFinger)
                    {
                        setShowFinger(true)
                        return
                    }
                    setShowInputPassword(true)
                    setTimeout(()=>{
                        inputPasswordRef && inputPasswordRef.current.focus()
                    },200)
                },
            },
            {
                title:"钱包同步",
                onPress:()=>{
                    console.log(1)
                },
            },
            {
                dividerBottom:true,
                title:"白名单",
                onPress:()=>{
                    console.log(1)
                },
            },
            {
                title:"指纹支付",
                onPress:()=>{
                    navigation.navigate("L2_SettingPayByFinger")
                },
            },
            {
                title:"修改密码",
                onPress:()=>{
                    console.log(1)
                },
            },
            {
                title:"重置密码",
                onPress:()=>{
                    console.log(1)
                },
            },
        ];
        setWalletDetailListItem(WalletDetailListItemTemp)
    }

    const fingerToNewView = async (checkFingerRes: boolean) => {
        try {
            if (!checkFingerRes) {
                setShowInputPassword(true)
                setTimeout(()=>{
                    inputPasswordRef && inputPasswordRef.current.focus()
                },100)
                return;
            }
            setShowInputPassword(false)
            let walletInfo = await getWalletInfo(nowWallet.chainID, nowWallet.address);
            if (!(walletInfo && walletInfo.privateKey)) {
                SimpleToast.show("地址私钥不存在")
                return;
            }
            if (toViewName === "") {
                SimpleToast.show("跳转页面出错")
                return;
            }
            let toViewData = {};
            if (toViewName === "L2_PrivateKeyView") {
                toViewData = {privateKey: walletInfo.privateKey};
            } else if (toViewName === 'L2_MnemonicView') {
                toViewData = {chainID: nowWallet.chainID, address: nowWallet.address}
            } else if (toViewName === 'L2_KeystoreView') {
                toViewData = {chainID: nowWallet.chainID, address: nowWallet.address}
            }
            navigation.navigate(toViewName, toViewData)
        } catch (e) {
            console.log(e)
        }
    }

    const deleteWallet = async () => {
        let walletInfo = await getWalletInfo(nowWallet.chainID,nowWallet.address);
        let removeWalletRes = await removeWallet(walletInfo)

        if(!removeWalletRes.success)
        {
            SimpleToast.show(removeWalletRes.falseReason);
            return ;
        }
        console.log(`deleteWallet`,removeWalletRes)
        await updateNewWallet()
    }
    const updateNewWallet = async () => {
        let chainInfo = await getChainInfo(nowWallet.chainID);
        if(chainInfo.walletList.length > 0) {
            let address = chainInfo.walletList[0];
            let nowWalletNew: useWalletType = {
                address,
                providerUrl: chainInfo.selectedProviderUrl,
                chainID: nowWallet.chainID
            }
            let updateNowWalletRes = await updateNowWallet(nowWalletNew)
            if (updateNowWalletRes) {
                navigation.goBack();
                return
            }
            SimpleToast.show(`updateNowWalletError:1`)
        }
        let netListTemp = await initNet();
        for(let i = 0 ; i < netListTemp.length ; i++)
        {
            let chainID = netListTemp[i].chainID;
            let chainInfoTemp = await getChainInfo(chainID)
            if(chainInfoTemp.walletList.length>0)
            {
                let address = chainInfoTemp.walletList[0];
                let nowWalletNew: useWalletType = {
                    address,
                    providerUrl: chainInfoTemp.selectedProviderUrl,
                    chainID
                }
                let updateNowWalletRes = await updateNowWallet(nowWalletNew)
                if (updateNowWalletRes) {
                    navigation.goBack();
                    return
                }
            }
        }
        await clearNowWallet()
        navigation.navigate("L2_Tabs")
        navigation.pop()
        navigation.navigate("L2_Tabs")
        SimpleToast.show(`没有可用地址`)

    }

    return (
        <View style={styles.container}>
            <ScrollView style={{width: "100%"}} fadingEdgeLength={20} showsVerticalScrollIndicator={false} nestedScrollEnabled={true}>
                <View style={styles.divider_20}/>
                <View style={styles.headerContainer}>
                    <Avatar source={((typeof img)==="number")?img:{uri:img}} rounded={true} activeOpacity={0.7}
                            containerStyle={{borderWidth: 0 / scale}} size={40}/>
                    <View style={styles.headerMsg}>
                        <View style={styles.headerNameLogo}>
                            <Text style={styles.headerName}>
                                {name}
                            </Text>
                            <SvgXml xml={writeGreySvgXml} width={20} height={20} style={{marginLeft:5,marginBottom:2}}/>
                        </View>
                        <View style={styles.headerAddrCopy}>
                            <Text style={styles.headerAddr}>
                                {address.slice(0,8)}...{address.slice(-8)}
                            </Text>
                            <SvgXml xml={copySvgXml} width={13} height={13} style={{marginLeft:5,marginTop:5}} onPress={()=>setCopyMsg(address)}/>
                        </View>
                    </View>
                </View>
                <View style={styles.divider_20}/>
                {
                    WalletDetailListItem.map((item,index)=>{
                        return (
                            item.show!==false?
                                <TouchableHighlight underlayColor={"grey"} onPress={item.onPress} key={index+"_MineList"}>
                                    <View style={item.dividerBottom?styles.listItem_dividerBottom:styles.pageView}>
                                        <View style={{flex:1,height:50,marginLeft:10,alignItems:"center",flexDirection:"row",borderBottomColor:"#f5f5f5",borderBottomWidth:1}}>
                                            <Text style={{flex:1,fontSize:fontSize_16}}>{item.title}</Text>
                                            <SvgXml xml={rightSvgXml()} width={25} height={25}/>
                                        </View>
                                    </View>
                                </TouchableHighlight>
                                :null
                        )
                    })
                }
                <Text style={styles.advanceMode}>
                    高级模式 >
                </Text>
            </ScrollView>
            <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                Alert.alert('删除钱包', '确定删除吗？', [{
                    text: "取消",
                    onPress: () => {
                        return
                    },
                    style: "cancel"
                }, {
                    text: "确认",
                    onPress:   () => {
                        deleteWallet()
                    }
                }],{cancelable: true});
            }}>
                <View style={styles.deleteBTN}>
                    <Text style={{fontSize:fontSize_14,color:"red"}}>删除钱包</Text>
                </View>
            </TouchableHighlight>
            <BottomSheet
                modalProps={{animationType:"fade"}}
                isVisible={showInputPassword}
            >
                <View style={{width:width,height:height-1,backgroundColor: 'rgba(0.5, 0.25, 0, 0.2)'}}>
                    <TouchableHighlight
                        underlayColor={"rgba(0.5, 0.25, 0, 0.2)"}
                        onPress={()=>{
                            setPasswordInput("")
                            setShowPassword(false)
                            setShowInputPassword(false)
                        }}
                        style={{flex:1,backgroundColor:"rgba(0.5, 0.25, 0, 0.2)",alignItems:"center",justifyContent:"center"}}
                    >
                        <TouchableHighlight underlayColor={"rgba(0.5, 0.25, 0, 0.2)"} style={{width:"100%"}}>
                            <View style={{borderRadius:5,width:"100%",alignItems:"center"}}>
                                <View style={{
                                    width:"80%",
                                    backgroundColor:"#f5f6f8",
                                    padding:20,
                                    borderTopRightRadius:5,
                                    borderTopLeftRadius:5,
                                    alignItems:"center",
                                    borderBottomWidth:1/scale,
                                    borderBottomColor:"#b4b5b7",
                                }}>
                                    <Text style={{fontSize:fontSize_16,fontWeight:"bold",marginBottom:20}}>输入密码</Text>
                                    <View style={{
                                        width:"100%",
                                        backgroundColor:"white",
                                        padding:5,
                                        borderRadius:5,
                                        borderWidth:1/scale,
                                        borderColor:"#bebfc1"}}>

                                        <TextInput
                                            secureTextEntry={!showPassword}
                                            placeholder={"请输入钱包密码"}
                                            style={{
                                                width:"80%",
                                                fontSize:fontSize_16,
                                                padding:0
                                            }}
                                            ref={ inputPasswordRef}
                                            autoFocus={false}
                                            onChangeText={(value)=>{setPasswordInput(value.trim())}}
                                        />

                                        <SvgXml xml={showPassword?openeyeSvgXml("#9c9c9c"):closeeyeSvgXml("#9c9c9c")} width={20} height={20} onPress={()=>{
                                            setShowPassword(!showPassword)
                                        }}
                                                style={{
                                                    position:"absolute",
                                                    right:15,
                                                    bottom:8
                                                }}
                                        />
                                    </View>
                                </View>
                                <View style={{
                                    width:"80%",
                                    height:45,
                                    backgroundColor:"#f5f6f8",
                                    borderBottomRightRadius:5,
                                    borderBottomLeftRadius:5,
                                    flexDirection:"row"
                                }}>
                                    <TouchableHighlight underlayColor={"#f5f6f8"} style={{flex:1,alignItems:"center",justifyContent:"center",borderRightWidth:1/scale,borderRightColor:"#b4b5b7"}}
                                                        onPress={()=>{
                                                            setPasswordInput("")
                                                            setShowPassword(false)
                                                            setShowInputPassword(false)
                                                        }}>
                                        <Text style={{fontSize:fontSize_14}}>
                                            取消
                                        </Text>
                                    </TouchableHighlight>
                                    <TouchableHighlight underlayColor={"#f5f6f8"} style={{flex:1,alignItems:"center",justifyContent:"center"}} onPress={async () => {
                                        try {
                                            let checkPasswordRes = await checkWalletPassword(nowWallet.chainID, nowWallet.address, passwordInput);
                                            if (!checkPasswordRes.success) {
                                                SimpleToast.show(checkPasswordRes.falseReason);
                                                return;
                                            }
                                            console.log(checkPasswordRes)
                                            setShowInputPassword(false)
                                            let walletInfo = await getWalletInfo(nowWallet.chainID,nowWallet.address);
                                            if(!(walletInfo && walletInfo.privateKey))
                                            {
                                                SimpleToast.show("地址私钥不存在")
                                                return ;
                                            }
                                            if(toViewName === "")
                                            {
                                                SimpleToast.show("跳转页面出错")
                                                return ;
                                            }
                                            let toViewData = {};
                                            if(toViewName === "L2_PrivateKeyView")
                                            {
                                                toViewData = {privateKey:walletInfo.privateKey};
                                            }
                                            else if(toViewName === 'L2_MnemonicView')
                                            {
                                                toViewData = {chainID:nowWallet.chainID,address:nowWallet.address}
                                            }
                                            else if(toViewName === 'L2_KeystoreView')
                                            {
                                                toViewData = {chainID:nowWallet.chainID,address:nowWallet.address}
                                            }
                                            navigation.navigate(toViewName,toViewData)
                                        } catch (e) {
                                            console.log(e)
                                        }
                                    }}>
                                        <Text style={{fontSize:fontSize_14}}>
                                            确认
                                        </Text>
                                    </TouchableHighlight>
                                </View>
                            </View>
                        </TouchableHighlight>
                    </TouchableHighlight>
                </View>
            </BottomSheet>
            {
                showFinger?
                    <FingerPrintPopup setShowFingerPrint={setShowFinger} dispatch={fingerToNewView}/>
                    :
                    null
            }

        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width:width,
        alignItems: "center",
        flexDirection: "column",
        backgroundColor:"#f6f6f6"
    },
    headerContainer:{
        width:width,
        height:80,
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"flex-start",
        backgroundColor:"white",
        paddingLeft:10,
        paddingRight:10
    },
    headerMsg:{
        flex:1,
        flexDirection:"column",
        marginLeft:10
    },
    headerNameLogo:{
        flexDirection:"row",
        flex:1,
        alignItems:"flex-end",
        // backgroundColor:"pink"
    },
    headerAddrCopy:{
        flexDirection:"row",
        flex:1,
        justifyContent:"flex-start",
        // alignItems:"flex-end",
        // backgroundColor:"pink"
    },
    headerName:{
        fontSize:fontSize_15,
        color:"#a6a6a6",
        lineHeight:25
    },
    headerAddr:{
        fontSize:fontSize_12,
        lineHeight:25
        // backgroundColor:"pink"
    },
    divider_20:{
        width:width,
        height:10,
        backgroundColor:"#f6f6f6"
    },
    divider_15:{
        width:width,
        height:15,
        backgroundColor:"#f6f6f6"
    },
    pageView:{
        width:width,
        height:55,
        backgroundColor:"white",
        flexDirection:"row",
        alignItems:"center",
        paddingLeft:10,
        paddingRight:10,
    },
    listItem_dividerBottom:{
        width:width,
        height:55,
        backgroundColor:"white",
        flexDirection:"row",
        alignItems:"center",
        paddingLeft:10,
        paddingRight:10,
        borderBottomWidth:10,
        borderBottomColor:"#f6f6f6",
    },
    advanceMode:{
        textAlign:"right",
        width:"100%",
        fontSize:fontSize_15,
        lineHeight:50,
        color:"#276fc2",
        paddingRight:20,
        paddingBottom:50
    },
    deleteBTN:{
        marginTop:20,
        marginBottom:20,
        width:width*0.85,
        height:40,
        backgroundColor:"white",
        alignItems:"center",
        justifyContent:"center"
    },
})

export default L2_WalletDetail;


